<template>
  <div>
    <j-modal
      :visible="visible"
      :title="title"
      :maskClosable="false"
      style="top:0"
      width="99vw"
      height="100vh"
      @ok="handleOk"
      @cancel="handleCancel">
      <a-form-model
        ref="form"
        :model="model"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol">
        <a-row>
          <a-col :span="span" >
            <a-form-model-item label="期间" prop="periodId">
              <j-dict-select-tag type="list" v-model="model.periodId" dictCode="period_dict,period_name,id" placeholder="请选择期间" @change="handleChangePeriod">

              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>

          <a-col :span="span" >
            <a-tabs type="card">

              <a-tab-pane tab="工时表">
                <!--工具栏-->
                <vxe-toolbar
                  :refresh="{query: getTimesheetList}">
                  <template v-slot:buttons>
                    <a-button type="primary" style="margin-right:10px" @click="insertEvent(-1)">增加</a-button>
<!--                    <a-button type="primary" style="margin-right:10px" @click="handleSave">保存</a-button>-->
                    <a-button v-if="disable" style="margin-right:10px"  @click="$refs.xTable1.removeCheckboxRow()">批量删除</a-button>
                  </template>
                </vxe-toolbar>
                <!--主表-->
                <vxe-table
                  ref="xTable1"
                  id="xTable1"
                  :export-config="{}"
                  :custom-config="{storage: true}"
                  highlight-hover-row
                  :data="tbTimesheetTable.dataSource"
                  :loading="tbTimesheetTable.loading"
                  :edit-config="tableEditConfig"
                  :edit-rules="validRules"
                  @checkbox-change="onSelectChange"
                  keep-source
                  show-footer
                  :footer-method="footerMethod"
                  footer-cell-class-name="col-blue"
                >
                  <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                  <vxe-table-column type="seq" width="50" title="序号"></vxe-table-column>
                  <vxe-table-column field="projectId" title="项目" width="200" show-overflow :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{customProjectRender(row.projectId)}}</span>
                    </template>
                    <template #edit="{ row }">
                      <j-search-select-tag
                        v-model="row.projectId"
                        dict="project_dict,project_name,isc"
                        placeholder="请选择项目"
                        :getPopupContainer="getModalAsContainer" />
                    </template>
                  </vxe-table-column>
                  <vxe-table-column field="stage" title="阶段" width="100" show-overflow :edit-render="{}">
                    <template #default="{ row }">
                      <span>{{customStageRender(row.stage)}}</span>
                    </template>
                    <template #edit="{ row }">
                      <j-dict-select-tag
                        type="list"
                        v-model="row.stage"
                        dictCode="project_stage"
                        placeholder="请选择阶段"
                        :getPopupContainer="getModalAsContainer"
                        />
                    </template>
                  </vxe-table-column>
                  <vxe-table-column v-for="(config, index) in tableColumn" :key="index" v-bind="config" :edit-render="{}">
                    <template #edit="{ row, column }">
                      <a-input v-model.number="row[column.property]" type="text"></a-input>
                    </template>
                  </vxe-table-column>
                </vxe-table>

              </a-tab-pane>
            </a-tabs>
            </a-col>
        </a-row>
      </a-form-model>
    </j-modal>
  </div>
</template>
<script>
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import JVxeInputCell from '@comp/jeecg/JVxeTable/components/cells/JVxeInputCell'
import {initDictOptions, filterDictText, filterDictTextByCache} from '@/components/dict/JDictSelectUtil'
import { getTimesheetList, getPeriodList, cudPeriodDetail, getCurrentDatePeriodId } from '@/api/timesheet'
import XEUtils from 'xe-utils'
const dayjs = require('dayjs');
import 'dayjs/locale/zh-cn';
import Vue from "vue";
dayjs.locale('zh-cn');

function handleDetailData(objects){
  let DetailDatas = [];


  // console.log('objects', JSON.parse(JSON.stringify(objects)))
  for(let i=0;i<objects.length;i++)
   {

    let list = [];
    let DetailData = {};
    let object = objects[i]
     Object.keys(object).forEach((key)=>{
      if(key.startsWith('workTime')){
        let tmpkey = key.replace('workTime','')

        if(parseInt(object[key]) != 0 && object[key] != null){
          list.push({
            'workdate':tmpkey,
            'worktime':object[key]
          })
        }

      }else {
        DetailData[key] = object[key]
      }
    })
    DetailData.tbTimesheetList = list
    DetailDatas.push(DetailData)
  }

  return DetailDatas
}
export default {
  name:'TsDetailModal',
  components: { JVxeInputCell },
  mixins: [JVxeTableModelMixin],
  data() {
    return {
      tableColumn:[],
      disable:false,
      tableEditConfig: { trigger: 'click', mode: 'row', enabled: true, showStatus: true },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      span: 24,
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      model:{
        periodId:''
      },
      title: "",
      visible: false,
      // 工时表
      tbTimesheetTable: {
        loading: false,
        dataSource: [],
      },
      DictOptions:{
        period:[],
        stage:[],
        project:[],
      },
      validRules : {}
    };
  },
  created() {
    this.initDictConfig()
  },
  methods: {
    sumNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    },
    footerMethod({columns, data}) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '∑合计'
          }
          let list = [];
          this.tableColumn.forEach(element=>{
            list.push(element.field)
          })
          if (list.includes(column.property)) {
            // return XEUtils.sum(data, column.property)
            return this.sumNum(data, column.property)
          }
          return null
        })
      ]
    },
    onSelectChange(selectedRowKeys) {
      const $table = this.$refs.xTable1
      const selectRecords = $table.getCheckboxRecords()
      if (selectRecords.length != 0 && selectRecords != null ) {
        this.disable = true
      }else {
        this.disable = false
      }
    },
    getModalAsContainer(node){
      return document.querySelector('.j-modal-box .ant-modal-content')
    },
    handleChangePeriod(){
      this.loadData();
    },
    async insertEvent(row){
      let record = {
        periodId:this.model.periodId
        }
      let {row: newRow} = await this.$refs.xTable1.insert(record, row)
      await this.$refs.xTable1.setActiveCell(newRow,'projectId')
    },
    async handleSave(){
      this.$refs.xTable1.validate((notPass)=> {
        if(!notPass){
          this.saveEvent()
        }
      })
    },
    async saveEvent(){
      const { insertRecords, updateRecords, removeRecords } = this.$refs.xTable1.getRecordset()
      cudPeriodDetail({
        'updateDetailData':handleDetailData(updateRecords),
        'addDetailData':handleDetailData(insertRecords),
        'deleteDetailData':removeRecords
      }).then((res)=>{
        if (res.success){
          this.$message.success(res.message)
          this.$emit('ok')
          this.loadData();
        }
      })
    },
    customStageRender(text){
      return filterDictText(this.DictOptions.stage, text)
    },
    customProjectRender(text){

      return filterDictText(this.DictOptions.project, text)
    },
    //DictOptions 自行定义
    initDictConfig() {
      //初始化字典 - 期间
      initDictOptions('period_dict,period_name,id').then((res) => {
        if (res.success) {
          this.DictOptions.period = res.result;
        }
      });
      //初始化字典 - 项目
      initDictOptions('project_dict,project_name,isc').then((res) => {
        if (res.success) {
          this.DictOptions.project = res.result;
        }
      });
      initDictOptions('project_stage').then((res) => {
        if (res.success) {
          this.DictOptions.stage = res.result;
        }
      });
    },
    addBefore() {
      this.tbTimesheetTable.dataSource=[]
      this.disable = false
    },
    add () {
      // this.addBefore()
      getCurrentDatePeriodId().then((res)=>{
          if(res.success){
            this.model.periodId = res.result

            this.loadData()
          }
      })
      this.visible = true

    },
    loadData(){
      this.tbTimesheetTable.loading=true
      let id = this.model.periodId
      // 表格日期表头
      getPeriodList({id:id}).then((res) =>{
        if(res.success) {
          this.tableColumn = [];

          //表头初始化
          let period = res.result
          for (let i = 0; i < 7; i++) {
            let field = 'workTime'+dayjs(period.startdate).add(i, 'day').format('YYYY-MM-DD')
            let title = dayjs(period.startdate).add(i, 'day').format('dddd') +'\n'+ dayjs(period.startdate).add(i, 'day').format('MM-DD')
            //初始化表头
            this.tableColumn.push({
              field: field,
              title: title
            });

          }

          //数据校验初始化
          this.validRules = {
            stage:[{
              required:true,message:'阶段必须填写'
            }],
            projectId:[{
              required:true,message:'项目必须填写'
            }],


          }

          this.tableColumn.forEach(e=>{
            //初始化验证
            Object.defineProperty(this.validRules,e.field,
              {value:
                [
                  {
                    type:'number',
                    min:0,
                    max:24,
                    message:'请输入工时0-24',
                    trigger:'blur'
                  }
                ]
              })
          })

          //表格数据准备
          this.getTimesheetList()
          setTimeout(() => {
            this.tbTimesheetTable.loading=false
          }, 500)

        }
      })
    },
    edit () {
      this.visible=true
      this.loadData()
    },
    validateError(msg){
      this.$message.error(msg)
    },
    async getTimesheetList(){
      this.disable = false
      let id = this.model.periodId

      return getTimesheetList( { periodId: id } ).then((res) =>
      {
        if(res.success) {
          let result = res.result
          let period = this.tableColumn
          //表格数据预处理
          for (let key in result) {
            let obj = {}
            for(let n in period){
              Vue.set(obj,period[n].field,0)
            }
            result[key] = Object.assign(obj, result[key])
          }
          this.tbTimesheetTable.dataSource = result
        }
      })
    },
    async handleOk() {
      // console.log(this.$refs.xTable1)
      let data = this.$refs.xTable1.footerData[0]
      for(let i = 4 ; i <= 10 ; i++){
        if(data[i] > 24) {
          return this.$message.error('每天可以填报的最大工作小时：【24小时】')
        }
      }
      this.$refs.xTable1.validate((notPass)=> {
        if(!notPass){
          this.saveEvent()
          this.visible = false;
        }
      })
    },
    handleCancel(e) {
      this.visible = false;
    }
  },
};
</script>
<style>
.col-blue {
  background-color: #E6E6E6;
}
</style>
